package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.core.util.ExcelFormatUtil;
import cn.stylefeng.guns.sys.modular.system.controller.BaseFrontController;
import cn.stylefeng.guns.sys.modular.system.entity.BtySalaryChange;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyArchivesMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.BtySalaryChangeMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.EmpAndDeptAndDingdingAttendParam;
import cn.stylefeng.guns.sys.modular.system.model.params.SalaryChangeParam;
import cn.stylefeng.guns.sys.modular.system.model.result.AttendAuditBtyAreaResult;
import cn.stylefeng.guns.sys.modular.system.model.result.DingdingEmpSimpleResult;
import cn.stylefeng.guns.sys.modular.system.service.BtySalaryChangeService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * 工资变动主表实现层
 *
 * @author: tianzhen
 * @date: 2022/7/14 14:54
 */
@Slf4j
@Service
public class BtySalaryChangeServiceImpl extends ServiceImpl<BtySalaryChangeMapper, BtySalaryChange> implements BtySalaryChangeService {

    @Resource
    private BtyArchivesMapper btyArchivesMapper;

    @Override
    public List<AttendAuditBtyAreaResult> getOperationManagerList(SalaryChangeParam salaryChangeParam) {
        return this.baseMapper.getOperationManagerList(salaryChangeParam);
    }

    @Override
    public List<AttendAuditBtyAreaResult> getSupervisorList(SalaryChangeParam salaryChangeParam) {
        return this.baseMapper.getSupervisorList(salaryChangeParam);
    }

    @Override
    public List<AttendAuditBtyAreaResult> getStoreList(SalaryChangeParam salaryChangeParam) {
        return this.baseMapper.getStoreList(salaryChangeParam);
    }

    @Override
    public List<String> getEmpListByStoreName(SalaryChangeParam salaryChangeParam) {
        return this.baseMapper.getEmpListByStoreName(salaryChangeParam.getStoreName());
    }

    @Override
    public LayuiPageInfo getSalaryChangePage(SalaryChangeParam salaryChangeParam) {
        Page pageContext = LayuiPageFactory.defaultPage();
        Page<BtySalaryChange> pageList = this.baseMapper.getSalaryChangePage(pageContext, salaryChangeParam);
        return LayuiPageFactory.createPageInfo(pageList);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData audit(SalaryChangeParam salaryChangeParam) {
        salaryChangeParam.setUpdateUser(LoginContextHolder.getContext().getUserId());
        int updateNum = this.baseMapper.batchUpdatePersonnelAuditStatusById(salaryChangeParam);
        if(updateNum > 0 && "3".equals(salaryChangeParam.getAuditStatus())){
            //获取申请单的员工信息
            List<BtySalaryChange> salaryChangeList = this.baseMapper.getSalaryChangeList(salaryChangeParam);
            //修改档案表中的岗位工资
            if(CollectionUtil.isNotEmpty(salaryChangeList)){
                btyArchivesMapper.updatePostWageByTelBh(salaryChangeList);
            }
        }
        return ResponseData.success();
    }

    @Override
    public ResponseEntity<byte[]> EmpSalaryChangeDataExport(HttpServletRequest request, HttpServletResponse response, SalaryChangeParam salaryChangeParam) {
        try {
            log.info(">>>>>>>>>>工资变动申请导出excel>>>>>>>>>>");
            BaseFrontController baseFrontController = new BaseFrontController();
            // 获取查询结果
            List<BtySalaryChange> resultList = this.baseMapper.getSalaryChangeList(salaryChangeParam);
            return baseFrontController.buildResponseEntity(exportEmp(resultList), "工资变动申请数据.xls");
        } catch (Exception e) {
            e.printStackTrace();
            log.error(">>>>>>>>>>工资变动申请导出excel 异常，原因为：" + e.getMessage());
        }
        return null;
    }

    private InputStream exportEmp(List<BtySalaryChange> list) {
        log.info(">>>>>>>>>>>>>>>>>>>>开始进入工资变动申请导出方法>>>>>>>>>>");
        ByteArrayOutputStream output = null;
        InputStream inputStream1 = null;
        // 保留1000条数据在内存中
        SXSSFWorkbook wb = new SXSSFWorkbook(1000);
        SXSSFSheet sheet = wb.createSheet();
        // 设置报表头样式cell样式
        CellStyle header = ExcelFormatUtil.headSytle(wb);
        // 报表体样式
        CellStyle content = ExcelFormatUtil.contentStyle(wb);
        // 每一列字段名
        String[] titles = new String[]{
                "序号",
                "店名",
                "妖码",
                "营运经理",
                "督导",
                "大店长",
                "店长",
                "员工姓名",
                "员工ID",
                "涨薪前基本工资",
                "涨薪前岗位工资",
                "涨(降)薪后岗位工资",
                "申请时间"};
        // 字段名所在表格的宽度，数量应与列字段名数量一致
        int[] ints = new int[]{2000, 6000, 3000, 3000, 3000, 3000, 3000, 3000, 5000, 4000, 4000, 4000, 6000};
        // 设置总标题内容，没有可略过
        // 设置内容标题
        //内容的标题所在行
        int concentitleStartRow = 1;
        //设置表头样式
        ExcelFormatUtil.initContentTitleEX(sheet, header, concentitleStartRow, titles, ints);
        log.info(">>>>>>>>>>>>>>>>>>>>表头样式设置完成>>>>>>>>>>");
        // 从第contentStartRow行开始为内容数据
        int contentStartRow = concentitleStartRow + 1;
        if (list != null && list.size() > 0) {
            int hangInx = 1;
            log.info(">>>>>>>>>>>>>>>>>>>>开始遍历数据组装单元格内容>>>>>>>>>>");
            for (int i = 0; i < list.size(); i++) {
                BtySalaryChange result = list.get(i);
                SXSSFRow row = sheet.createRow(contentStartRow + i - 1);
                int j = 0;
                // 1.序号
                SXSSFCell cell = row.createCell(j++);
                ExcelFormatUtil.setCellVal(hangInx, content, cell);
                //2.店名
                cell = row.createCell(j++);
                ExcelFormatUtil.setCellVal(result.getStoreName(), content, cell);
                //3.妖码
                cell = row.createCell(j++);
                ExcelFormatUtil.setCellVal(result.getYaoma(), content, cell);
                //4.营运经理
                cell = row.createCell(j++);
                ExcelFormatUtil.setCellVal(result.getOperationManager(), content, cell);
                //5.督导
                cell = row.createCell(j++);
                ExcelFormatUtil.setCellVal(result.getSupervisor(), content, cell);
                //6.大店长
                cell = row.createCell(j++);
                ExcelFormatUtil.setCellVal(result.getBigStoreManager(), content, cell);
                //7.店长
                cell = row.createCell(j++);
                ExcelFormatUtil.setCellVal(result.getStoreManager(), content, cell);
                //8.员工姓名
                cell = row.createCell(j++);
                ExcelFormatUtil.setCellVal(result.getEmpName(), content, cell);
                //9.员工ID
                cell = row.createCell(j++);
                ExcelFormatUtil.setCellVal(result.getEmpBh(), content, cell);
                //10.涨薪前基本工资
                cell = row.createCell(j++);
                ExcelFormatUtil.setCellVal(result.getBaseWage(), content, cell);
                //11.涨薪前岗位工资
                cell = row.createCell(j++);
                ExcelFormatUtil.setCellVal(result.getPostWage(), content, cell);
                //12.涨(降)薪后岗位工资
                cell = row.createCell(j++);
                ExcelFormatUtil.setCellVal(result.getChangePostWage(), content, cell);
                //13.申请时间
                cell = row.createCell(j++);
                ExcelFormatUtil.setCellVal(DateUtil.getDate(result.getCreateTime()), content, cell);
                hangInx = hangInx + 1;
            }
            log.info(">>>>>>>>>>>>>>>>>>>>结束遍历数据组装单元格内容>>>>>>>>>>");
        }
        try {
            output = new ByteArrayOutputStream();
            wb.write(output);
            inputStream1 = new ByteArrayInputStream(output.toByteArray());
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (output != null) {
                    output.close();
                    if (inputStream1 != null) {
                        inputStream1.close();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return inputStream1;
    }

}
